<template>
	<div class="userFacedetection">
		<!-- <narBar  :incon="!!route.query.isShare?'arrows':'xMark'" :back="back" @goBack="goBack(!!route.query.isShare?1:2)"
			:title="'人脸检测'"></narBar> -->
			<div class="topBar">
				<customNavBar :leftTetx="leftTetx" :titleTest="titleTest" :H5="true" @goBack="goBack(!!route.query.isShare?1:2)"></customNavBar>
			</div>
		<div class="contentOut">
			<div class="content" :class="statusFlag == 2
			? 'havestatusAndNavigator'
			: statusFlag == 1
				? 'havestatusOrNavigator'
				: ''
			">
			<div class="userValidation-content">
				<p v-if="btnTitleFlag == '1'">
					请保持正脸在取景框中，根据屏幕指示完成识别
				</p>
				<div v-if="btnTitleFlag == '1'">
					<useFaceMsg ref="divCamera" />
				</div>
				<div v-if="btnTitleFlag != '1'" class="face-Failed" style="margin-bottom: 20%; margin-top: 18%">
					<div class="video-div">
						<div class="img_bg_camera">
							<img class="face-failed-img" src="" alt="" style="width: 153.5px; height: 153.5px" />
						</div>
					</div>
					<div class="msg">
						<span>认证未通过，再试一次吧</span>
					</div>
				</div>
				<div class="buttonOut" >
					<!-- :loading="yzLoading" -->
					<van-button block square class="primaryButton" type="primary" @click.stop="submitBtn">{{
			btnTitleFlag == '1' ? '验证' : '再试一次'
		}}</van-button>
					<van-button v-show="btnTitleFlag != '1'" block square class="imgSrcTrue" type="primary"
						@click.stop="delPhoto">取消</van-button>
				</div>
			</div>
		</div>
		</div>
	</div>
</template>
<script lang="ts" setup name="userFacedetection">
import customNavBar from "/src/components/NavBar/customNavBar.vue"
import narBar from '/@/components/common/narBar.vue'
import useFaceMsg from '/@/components/Auth/useFaceMsg.vue'
import { subFace, CustomerInfoByTaskCode } from '/@/api/index'
import { confirmDialog } from '/@/utils/reviewH5/Message'
import { recordStateNotification } from '/@/assets/js/mergeH5/utils'
import { loginCallBack, agreementStatus } from '/@/assets/js/comApiMethods'
import {
	recordUserBehavior,
	isShowStatusAndNavigator,
} from '/@/assets/js/utils'
import { userInfoStrore } from '/@/stores/userInfoStore'
import { policyListStore } from '/@/stores/policyListStore'
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
import { ref, nextTick } from 'vue'
import { onMounted, onUnmounted } from 'vue'
import { userInfo } from 'os'
import { log } from 'console'
import { convertCompilerOptionsFromJson } from 'typescript'
import { taskInvitationInfo, createCustomMark } from '/@/api/auth/repot'

const store = userInfoStrore()
const pStore = policyListStore()
const statusFlag = isShowStatusAndNavigator()
const route = useRoute()
const router = useRouter()
//首次授权需要扫人脸，query里面会传一个参数，如果没有是正常流程，存在即表示人脸成功后返回上一级
const isShare = ref(route.query.isShare as any)
let customerInfo = ref("")
const leftTetx = ref<string>("");
const titleTest = ref<string>("人脸检测");

const btnTitleFlag = ref('1') // 1是验证，2是再次验证
const yzLoading = ref(false)
const back = ref(false)
const divCamera = ref()
const goBack = (type: any) => {
	if (type == '1') {
		router.go(-1)
	} else {
		if (back.value) {
			delPhoto()
		} else {
			confirmDialog(router)
		}
	}
}
const callbackSuccess = async () => {
	// 人脸校验成功后，获取个人的唯一标识
	createCustomMark({ taskCode: pStore.taskNo }).then((rest: any) => {
		if (rest.code == 200) {
			sessionStorage.removeItem('customToken')
			sessionStorage.setItem('customToken', rest.customToken)
			router.push({
				path: '/Rlist',
			})
		}
	})
}
const submitBtn = async () => {
	// 提交人脸识别的照片
	if (btnTitleFlag.value == '2') {
		// 验证是否是再试一次
		openCamera()
		back.value = false
		return
	}
	const img = await divCamera.value.drawImage()
	divCamera.value.stopNavigator()
	yzLoading.value = true
	// const img = "ceshi "
	let obj = !!isShare.value ? { taskCode: route.query.taskCode, isShare: isShare?.value, ...customerInfo } : { ...store.userInfoObj }
	let newobj = {
		face: img,
		...obj
	}
	let params: any = JSON.stringify(newobj)
	subFace(params).then(async (res: any) => {
		if (res.code == 200 && res.data.result) {
			//jstgzt
			//如果会话里面存在ISGongzuo，表示走的是金事通的工作台的获取验证码,走完人间识别后直接去一个固定页面
			if(!!sessionStorage.getItem('ISGongzuo')){
				var z = sessionStorage.getItem('taskCode')
				taskInvitationInfo({taskCode: z}).then((v: any) => {
					if (v.code == 200) {
						router.push({
							name: 'jstReportingResultShare',
							query: {
								taskCode: z,
								reportType: v.data.reportType,
								userType: v.data.userType,
								isYsc:1,
							},
						})
					}
				});
				// http://localhost:8080/policyReviewH5/reportingResultShare?taskCode=&reportType=2&userType=03&isYsc=1
				// router.push({
				// 	path: "/status/error"   //改这个
				// })
			}else{
				//首次授权需要扫人脸，query里面会传一个参数isShare，如果没有是正常流程，存在即表示人脸成功后返回上一级
				if (!!isShare.value) {
					router.go(-2)
					return
				}
				if (pStore.taskType == '1') {
					recordStateNotification(pStore.taskNo).then(async (res: any) => {
						callbackSuccess()
					})
						.catch((error: any) => {
							router.push({
								path: "/status/error"
							})
						})
				} else {
					callbackSuccess()
				}
			}
		} else {
			// 验证失败
			yzLoading.value = false
			btnTitleFlag.value = '2'
			back.value = true
		}
	})
}
const openCamera = () => {
	// 开启摄像头
	btnTitleFlag.value = '1'
	yzLoading.value = true
	nextTick(async () => {
		await divCamera.value.openCamera()
		yzLoading.value = false
	})
}
const delPhoto = () => {
	router.push({
		path: '/userConfirmation',
	})
}
let uid = ''
// 根据路由里带的toskcode获取三要素
const getCustomerInfoByTaskCode = async () => {
	CustomerInfoByTaskCode({ taskCode: route.query.taskCode }).then(async (res: any) => {
		if (res.code == 200) {
			customerInfo = res.data
		} else {
			// console.log("获取三要素失败")
		}
	})
}
onMounted(() => {
	if (!!isShare.value) {
		//获取三要素
		getCustomerInfoByTaskCode()
	}
	openCamera()
	recordUserBehavior('', '1', '人脸识别拍摄', (uuid: any) => {
		uid = uuid
	})
})
onUnmounted(() => {
	recordUserBehavior(uid, '2', '人脸识别拍摄', (uuid: any) => {
	})
})
onBeforeRouteLeave((to, form, next) => {
	try {
		divCamera.value.stopNavigator() // 关闭摄像头
	} catch { }
	next()
})
</script>

<style lang="less" scoped>
:deep(.van-button) {
	height: 44px;
	border-radius: 5px;
	font-size: 18px;
	color: #ffffff;
	font-weight: 400;
	line-height: 44px;
	font-family: PingFangSC-Regular, PingFang SC;
}

.imgSrcTrue {
	color: #3e2e18;
	background-color: #ffffff;
	border: none;
}

.userFacedetection {
	width: 100vw;
	max-width: 600px;
	margin: 0 auto;
	overflow: hidden;
	background: #fff;
	box-sizing: border-box;
	font-family: PingFangSC-Regular, PingFang SC;
	.topBar{
		width: 100%;
		height: 50px;
		background-color: #fff;
		margin-bottom: 25px;
		position: fixed;
		z-index: 1000;

	}
	.contentOut{
		width: 100%;
        overflow-x: hidden;
        overflow-y: scroll;
        // min-height: 100%;
		height: calc(100% - 60px);
		margin-top: 50px;
        box-sizing: border-box;
        // background-color: #F5F7FA;
		.content {
			margin: 14px;
            box-sizing: border-box;
            background-color: #fff;
			
	
			&.havestatusAndNavigator {
				// padding-top: 155.5px;
				padding-top: 55.5px;
				padding-bottom: 110px;
			}
	
			&.havestatusOrNavigator {
				// padding-top: 111.5px;
				padding-top: 11.5px;
				padding-bottom: 11.5px;
			}
		}
	}

	.userValidation-content {
		padding-bottom: 30px;
	}

	p {
		width: 100%;
		font-size: 14px;
		font-weight: 400;
		color: #333333;
		line-height: 20px;
	}

	.face-Failed {
		.video-div {
			margin: 40px auto 0px;
			width: 200px;
			height: 200px;
			padding: 0;
			display: flex;
			justify-content: center;

			.img_bg_camera {
				border-radius: 139.5px / 139.5px;
				overflow: hidden;
			}
		}

		.face-failed-img {
			content: @face-failed-img;
		}

		.msg {
			font-size: 18px;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #333333;
			line-height: 25px;
		}
	}
	.buttonOut{
            // width: 360px;
			width: 93vw;
			max-width: 360px;
            margin:  0 auto;
            margin-bottom:30px;
            padding: 0 10px;
            box-sizing: border-box;
			
        }
        .van-button {
            &.primaryButton {
                border-radius: 20px !important;
                background-color: #3296FA;
            }
        }
}
</style>
